package teacher

import (
	"anban/controllers"
	"anban/service"
	"anban/utils"
	"encoding/json"
	"fmt"
	"html/template"
)

type ClassController struct {
	controllers.BaseController
}

func (c *ClassController) Detail() {
	id := c.Ctx.Input.Param(":id")

	p := map[string]interface{}{}
	p["id"] = id
	c.Data["classInfo"] = service.GetClassInfo(p)

	p = map[string]interface{}{}
	p["classId"] = id
	p["status"] = 1
	c.Data["studentNum"], c.Data["studentList"] = service.GetStudentList(p)

	c.Data["title"] = "班级成员"
	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "teacher/class-detail.html"
}

func (c *ClassController) Add() {
	p := map[string]interface{}{}
	p["level"] = 1
	_, provinceList := service.GetRegionList(p)
	provinceValues := service.GetRegionListValues(provinceList)
	res, _ := json.Marshal(provinceValues)
	c.Data["provinceJson"] = string(res)

	p = map[string]interface{}{}
	_, courseList := service.GetCourseList(p)
	courseValues := service.GetCourseListValues(courseList)
	res, _ = json.Marshal(courseValues)
	c.Data["courseJson"] = string(res)

	c.Data["title"] = "新增班级"
	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "teacher/add-class.html"
}

func (c *ClassController) DoAdd() {
	var res *utils.ResJsonStruct
	input := c.Input()
	if len(input["province_id"][0]) <= 0 {
		res = utils.ResJson(0, "请选择省", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(input["city_id"][0]) <= 0 {
		res = utils.ResJson(0, "请选择市", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(input["district_id"][0]) <= 0 {
		res = utils.ResJson(0, "请选择区/县", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(input["school_id"][0]) <= 0 {
		res = utils.ResJson(0, "请选择学校", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(input["class_id"][0]) <= 0 {
		res = utils.ResJson(0, "请选择班级", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(input["course_id"][0]) <= 0 {
		res = utils.ResJson(0, "请选择科目", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	userId := c.GetSession("userId")

	p := map[string]interface{}{}
	p["userId"] = userId
	p["classId"] = input["class_id"][0]
	userClass := service.GetUserClassInfo(p)
	if userClass.Id > 0 {
		res = utils.ResJson(0, "新增失败，您已经添加过这个班级了", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	input["user_id"] = []string{fmt.Sprintf("%d", userId)}
	_, err := service.AddUserClass(input)
	if err != nil {
		res = utils.ResJson(0, "新增失败" + err.Error(), "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	res = utils.ResJson(1, "新增成功", "")
	c.Data["json"] = res
	c.ServeJSON()
}
